const {contextBridge,ipcRenderer} = require('electron')

// vue发送消息给主进程
const sendUrl = async(url) => {
    console.log('preload接受url:'+url)
    let result = await ipcRenderer.invoke('on-url-event',url)
    return result
}

// vue发送消息给主进程
const alert = async (msg) =>{
    await ipcRenderer.invoke('on-alert-event',msg)
}

// vue发送消息给主进程
const openDevTools = ()=>{
    ipcRenderer.invoke('on-open-dev-tool-event')
}

// vue发送消息给主进程
const log = (...args)=>{
    ipcRenderer.invoke('on-log-event',...args)
}

// vue发送消息给主进程
const openWindow = (url)=>{
    ipcRenderer.invoke('on-open-window-event',url)
}

// vue发送消息给主进程
const getImagelist = async ()=>{
    const fileList =  await ipcRenderer.invoke('on-get-image-list-event')
    return fileList
}

// 用来防止重复注册
let messageListener = null

// 主进程主动发送消息给vue
const onOpenDialogEvent = (callback)=>{
    // 监听来自主进程的消息
    if(ipcRenderer.eventNames().includes('message') 
    && messageListener !== null){
        console.log('移除message事件')
        ipcRenderer.removeListener('message',messageListener)
         messageListener = null
    }
   
    if(messageListener === null){
        messageListener = (event,msg)=>{
            callback(msg)
        }      
    }
    
    console.log('注册message事件')
    ipcRenderer.on('message', messageListener)
}


contextBridge.exposeInMainWorld('myApi',{
    sendUrl,
    alert,
    openDevTools,
    log,
    openWindow,
    getImagelist,
    onOpenDialogEvent
})